<template>
  <div class="track-container">
    <n-grid :cols="24" :x-gap="12" style="height: calc(100vh - 150px)">
      <!-- 左侧组织机构树 -->
      <n-gi :span="6">
        <OrgTree
          ref="orgTreeRef"
          @set="handleOrgSelect"
          @reload="handleOrgReload"
          @loaded="handleOrgTreeLoaded"
        />
      </n-gi>

      <!-- 右侧股道表格 -->
      <n-gi :span="18">
        <BusTable
          ref="trackTableRef"
          :columns="columns"
          :row-key="(row) => row.trackId"
          :scroll-x="1200"
          :pagination-config="{ pageSize: 20 }"
          :search-schemas="searchSchemas"
          :form-schemas="formSchemas"
          :form-rules="rules"
          :api-methods="apiMethods"
          :auto-load="false"
          modal-title="股道管理"
          @success="handleSuccess"
          @error="handleError"
        />
      </n-gi>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick } from 'vue';
  import { useMessage } from 'naive-ui';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import BusTable from '@/views/businessPages/comp/busTable/index.vue';

  // 导入API方法
  import {
    getTrackList,
    addTrack,
    updateTrack,
    deleteTrack,
    batchDeleteTracks,
  } from '@/api/business/stationManager/track';

  import { selectAllByType } from '@/api/business/dist';

  const message = useMessage();
  const orgTreeRef = ref();
  const trackTableRef = ref();

  // 当前选中的组织ID
  const selectedOrgId = ref<string>('');

  // 添加一个 ref 来标识组织树是否已加载
  const orgTreeLoaded = ref(false);

  // 表格列配置
  const columns = [
    {
      type: 'selection',
      disabled(row: any) {
        return row.name === 'disabled';
      },
    } as any,
    {
      title: '序号',
      key: 'id',
      width: 80,
      fixed: 'left',
      render: (row: any, index: number) => {
        // 通过tableRef获取分页信息计算序号
        const pagination = trackTableRef.value?.getPaginationRef?.();
        if (pagination) {
          const currentPage = pagination.page || 1;
          const pageSize = pagination.pageSize || 20;
          return (currentPage - 1) * pageSize + index + 1;
        }
        // 如果获取不到分页信息，使用默认计算方式
        return index + 1;
      },
    },
    {
      title: '股道名称',
      key: 'trackName',
      width: 150,
    },
    {
      title: '股道类型',
      key: 'trackTypeName',
      width: 150,
    },
    {
      title: '股道长度',
      key: 'trackLength',
      width: 120,
    },
    {
      title: '所属机构',
      key: 'orgName',
      width: 200,
    },
    {
      title: '机构全路径',
      key: 'orgArrayName',
      width: 250,
    },
    {
      title: '创建时间',
      key: 'createTime',
      width: 180,
    },
    {
      title: '更新时间',
      key: 'updateTime',
      width: 180,
    },
  ];

  // 搜索表单配置
  const searchSchemas = [
    {
      field: 'trackName',
      component: 'NInput',
      label: '股道名称',
      componentProps: {
        placeholder: '请输入股道名称进行搜索',
      },
    },
    {
      field: 'trackType',
      component: 'NSelect',
      label: '股道类型',
      asyncOptions: async () => {
        // 从接口获取选项数据
        let params = {
          type: 'proj_track@type',
        };
        const result = await selectAllByType(params);
        const res = result.map((item) => ({
          label: item.dictLabel,
          value: item.dictValue,
        }));
        return res;
      },
      componentProps: {
        placeholder: '请选择股道类型',
        // options: [
        //   { label: '货物线', value: '3' },
        //   { label: '到发线', value: '1' },
        //   { label: '调车线', value: '2' },
        //   { label: '其他', value: '4' },
        // ],
      },
    },
  ];

  // 表单配置
  const formSchemas = [
    {
      field: 'trackName',
      component: 'NInput',
      label: '股道名称',
      placeholder: '请输入股道名称',
      componentProps: {
        clearable: true,
      },
    },
    {
      field: 'trackType',
      component: 'NSelect',
      label: '股道类型',
      asyncOptions: async () => {
        // 从接口获取选项数据
        let params = {
          type: 'proj_track@type',
        };
        const result = await selectAllByType(params);
        const res = result.map((item) => ({
          label: item.dictLabel,
          value: item.dictValue,
        }));
        return res;
      },
      componentProps: {
        placeholder: '请选择股道类型',
        // options: [
        //   { label: '货物线', value: '3' },
        //   { label: '到发线', value: '1' },
        //   { label: '调车线', value: '2' },
        //   { label: '其他', value: '4' },
        // ],
      },
    },
    {
      field: 'trackLength',
      component: 'NInputNumber',
      label: '股道长度',
      componentProps: {
        placeholder: '请输入股道长度',
        min: 0,
      },
    },
    {
      field: 'orgId',
      component: 'NInput',
      label: '所属机构',
      placeholder: '请选择所属机构',
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'remark',
      component: 'NInput',
      label: '备注',
      placeholder: '请输入备注信息',
      componentProps: {
        type: 'textarea',
        rows: 3,
      },
    },
  ];

  // 表单验证规则
  const rules = {
    trackName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入股道名称',
    },
    trackType: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择股道类型',
    },
    orgId: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择所属机构',
    },
  };

  // API 方法配置
  const apiMethods = {
    getList: getTrackList,
    add: addTrack,
    update: updateTrack,
    delete: deleteTrack,
    batchDelete: batchDeleteTracks,
  };

  // 处理组织树加载完成事件
  function handleOrgTreeLoaded() {
    orgTreeLoaded.value = true;
    // 获取根节点并初始化表格
    initializeTableWithRootNode();
  }

  // 处理组织机构选择
  function handleOrgSelect(id: string, name: string) {
    selectedOrgId.value = id;
    // 更新表格搜索条件中的组织ID
    if (trackTableRef.value) {
      // 触发表格重新加载，传入orgId参数
      trackTableRef.value.reload({ orgId: id });
    }
  }

  // 处理组织树重新加载
  function handleOrgReload() {
    console.log('组织树重新加载完成');
  }

  // 处理新增股道
  function handleAdd() {
    if (!selectedOrgId.value) {
      message.warning('请先选择一个组织机构');
      return;
    }

    // 设置表单中的默认组织ID
    if (trackTableRef.value) {
      trackTableRef.value.setFormModel({ orgId: selectedOrgId.value });
    }
  }

  // 处理操作成功
  function handleSuccess(operation: string) {
    const operationMap = {
      add: '新增',
      update: '编辑',
      delete: '删除',
      'batch-delete': '批量删除',
    };

    message.success(`${operationMap[operation] || operation}操作成功`);
    // 操作成功后重新加载数据，保持当前orgId过滤条件
    if (trackTableRef.value) {
      trackTableRef.value.reload({ orgId: selectedOrgId.value });
    }
  }

  // 处理操作失败
  function handleError(error: any) {
    message.error('操作失败: ' + (error.message || '未知错误'));
  }

  // 初始化表格数据
  async function initializeTableWithRootNode() {
    if (orgTreeRef.value && typeof orgTreeRef.value.getRootNodeId === 'function') {
      const rootId = orgTreeRef.value.getRootNodeId();
      if (rootId) {
        selectedOrgId.value = rootId;
        if (trackTableRef.value) {
          trackTableRef.value.setDefaultParams({ orgId: rootId });
          trackTableRef.value.enableDataLoad();
          trackTableRef.value.reload({ orgId: rootId });
        }
      }
    }
  }

  // 组件挂载后初始化
  onMounted(async () => {
    // 等待组织树加载完成
    await nextTick();
    // 如果组织树已经加载完成，则直接初始化表格
    if (orgTreeLoaded.value) {
      initializeTableWithRootNode();
    }
  });
</script>

<style scoped>
  .track-container {
    padding: 16px;
    height: 100%;
    box-sizing: border-box;
  }

  :deep(.n-card) {
    height: 100%;
  }

  :deep(.n-data-table) {
    height: calc(100% - 100px);
  }
</style>
